﻿using System.Security.Claims;
using System.Threading.Tasks;
using ESoft.Core.Web.Common.Filters;
using ESoft.Core.Web.Config;
using ESoft.Core.Web.VO;
using ESoft.Portal.Data.Service;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;

namespace ESoft.Portal.Controllers
{
    [SkipUserAuthorize]
    public class LoginController : Controller
    {
        private readonly ILoginService _loginService;

        public LoginController(ILoginService loginService)
        {
            this._loginService = loginService;
        }

        public IActionResult Index()
        {
            return View();
        }


        [HttpPost]
        public async Task<IActionResult> Index(string mobilePhone, string userPwd)
        {
            var user = _loginService.Login(mobilePhone, userPwd);

            var claims = new[]
            {
                new Claim(nameof(user.UserName), user.UserName),
                new Claim(nameof(user.UserId), user.UserId),
                new Claim(nameof(user.UserType), user.UserType.ToString()),
                new Claim(nameof(user.ShopId), user.ShopId.ToString())
            };

            var claimsIdentity = new ClaimsIdentity(claims, WebParameter.UserAuthenticationScheme);
            ClaimsPrincipal userPrincipal = new ClaimsPrincipal(claimsIdentity);
            await HttpContext.SignInAsync(WebParameter.UserAuthenticationScheme, userPrincipal);

            return Json(ResponseResult.Success(user));
        }

        public async Task<IActionResult> Logout(string returnurl)
        {
            await HttpContext.SignOutAsync(WebParameter.UserAuthenticationScheme);
            return Redirect(returnurl ?? "~/Admin/Home/Index");
        }
    }
}
